package com.atguigu.gmall.activity.service.impl;

import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private RedisTemplate redisTemplate;

    //查询所有秒杀商品
    @Override
    public List<SeckillGoods> findAll() {
        return redisTemplate.opsForHash().values((RedisConst.SECKILL_GOODS));
    }

    //查询秒杀商品
    @Override
    public SeckillGoods getSeckillGoods(Long skuId) {
        return (SeckillGoods) redisTemplate.opsForHash().get(RedisConst.SECKILL_GOODS, skuId.toString());
    }

    @Override
    public Result checkOrder(Long skuId, String userId) {
        // 用户在缓存中存在，有机会秒杀到商品
        boolean isExist = redisTemplate.hasKey(RedisConst.SECKILL_USER + userId);
        if (isExist) {
            //判断用户是否正在排队
            //判断是否已经下单
            boolean isExistOrder = redisTemplate.hasKey(RedisConst.SECKILL_ORDERS_USERS + userId);
            if (isExistOrder) {
                String orderId = (String) redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
                return Result.build(orderId, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
            //判断用户是否下单
            boolean isHasKey = redisTemplate.hasKey(RedisConst.SECKILL_ORDERS + userId);
            if (isHasKey) {
                //抢单成功
                OrderRecode orderRecode = (OrderRecode) redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
                // 秒杀成功！
                return Result.build(orderRecode, ResultCodeEnum.SECKILL_SUCCESS);
            }
        }

        String state = (String) CacheHelper.get(skuId.toString());
        if ("0".equals(state)) {
            //已售罄 抢单失败
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }

        //正在排队中
        return Result.build(null, ResultCodeEnum.SECKILL_RUN);
    }
}
